package com.ouli.crowd.util;

import com.ouli.crowd.constant.CrowdConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 尚筹网项目通用的工具方法类
 * @author akai
 *
 */
public class CrowdUtil {
    /**
     * 判断当前请求是否为ajax请求
     * @param request
     * @return
     *      true:当前请求是ajax请求
     *      false:当前请求不是ajax请求
     */
    public static boolean judgeRequestType(HttpServletRequest request) {
        // 1.获取请求消息头
        String acceptHeader = request.getHeader("Accept");
        String xRequestHeader= request.getHeader("X-Requested-With");
        // 2.判断
        return (acceptHeader!=null && acceptHeader.contains("application/json"))
                ||
                (xRequestHeader != null && xRequestHeader.equals("XMLHttpRequest"));
    }

    /**
     * 对明文字符串进行MD5加密
     * @param source 传入的明文字符串
     * @return 加密的结果
     */
    public static String md5(String source) {

        // 1.先判断source是否有效
        if (source == null || source.length() == 0) {
            //2.如果不是有效的字符串跑出异常
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }
        // 3.获取一个MessageDigest对象

        try {
            String algorithm = "md5";
            MessageDigest messageDigest =  MessageDigest.getInstance(algorithm);
            // 4.获取明文字符串对应的字节数组
            byte[] input = source.getBytes();
            // 5.执行加密
            byte[] output = messageDigest.digest(input);
            // 6.创建BigInteger对象
            int sigNum = 1;
            BigInteger bigInteger = new BigInteger(sigNum,output);
            // 7.按照16进制将BigInteger的值转换成字符串
            int radix = 16;
            String encoded = bigInteger.toString(radix);
            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
